package com.example.pay.service.channel;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.example.pay.dto.PrepayResponse;
import com.example.pay.entity.MemberOrder;
import com.example.pay.entity.MemberPackageItem;
import com.example.pay.entity.UserPoints;
import com.example.pay.entity.UserPointsLog;
import com.example.pay.mapper.MemberOrderMapper;
import com.example.pay.mapper.UserPointsLogMapper;
import com.example.pay.mapper.UserPointsMapper;
import com.example.pay.service.NotifyService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

@Service
@RequiredArgsConstructor
public class PointsPayService implements ChannelPayService {
    private final NotifyService notifyService;
    private final MemberOrderMapper orderMapper;
    private final UserPointsMapper userPointsMapper;
    private final UserPointsLogMapper userPointsLogMapper;
    private final TransactionTemplate transactionTemplate;

    @Override
    public PrepayResponse prepay(MemberOrder order, MemberPackageItem item) {
        order.setPayStatus(1);
        // 扣减自己积分
        UserPointsLog userPointsLog = new UserPointsLog();
        userPointsLog.setPoints(order.getPayAmount().intValueExact());
        userPointsLog.setUserName(order.getUserName());
        userPointsLog.setUid(order.getUserId());
        userPointsLog.setMobile(order.getUserPhone());
        userPointsLog.setOperateType(2); // 扣减
        userPointsLog.setOrderId(order.getId().toString());

        LambdaUpdateWrapper<UserPoints> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(UserPoints::getUid,order.getUserId());
        wrapper.setSql("available_points = available_points - " + order.getPayAmount());
        wrapper.setSql("total_points = total_points - " + order.getPayAmount());
        transactionTemplate.execute(e->{
            orderMapper.updateById(order);
            // 开通对应的业务权限
            notifyService.createMemberPermissions(order);
            userPointsLogMapper.insert(userPointsLog);
            userPointsMapper.update(null,wrapper);
            return true;
        });
        return null;
    }
}
